package com.liao.seckill.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.liao.seckill.pojo.User;
import com.liao.seckill.service.UserService;
import com.liao.seckill.util.CookieUtil;
import com.liao.seckill.vo.RespBean;
import com.liao.seckill.vo.RespBeanEnum;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * @author lzp
 * @version 1.0
 * lzpnb!
 */
@Component
public class AccessLimitInterceptor implements HandlerInterceptor {

    @Resource
    private UserService userService;
    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(handler instanceof HandlerMethod) {
            User user = getUser(request, response);
            UserContext.setUser(user);

            HandlerMethod hm = (HandlerMethod) handler;
            AccessLimit accessLimit = hm.getMethodAnnotation(AccessLimit.class);

            if(accessLimit == null) {
                return true;
            }

            int second = accessLimit.second();
            int maxCount = accessLimit.maxCount();
            boolean needLogin = accessLimit.needLogin();

            if(needLogin) {
                if(user == null) {
                    render(response,RespBeanEnum.SESSION_ERROR);
                    return false;
                }
                String uri = request.getRequestURI();
                String key = uri + ":" + user.getId();
                ValueOperations valueOperations = redisTemplate.opsForValue();
                Integer count =(Integer) valueOperations.get(key);
                if(count == null) {
                    valueOperations.set(key,1,second, TimeUnit.SECONDS);
                }else if (count < maxCount) {
                    valueOperations.increment(key);
                }else {
                    render(response,RespBeanEnum.ACCESS_LIMIT_REACHED);
                    return false;
                }

            }

        }
        return true;
    }

    private void render(HttpServletResponse response,RespBeanEnum respBeanEnum) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        RespBean error = RespBean.error(respBeanEnum);
        out.write(new ObjectMapper().writeValueAsString(error));
        out.flush();
        out.close();
    }


    private User getUser(HttpServletRequest request,HttpServletResponse response) {
        String ticket = CookieUtil.getCookieValue(request, "userTicket");
        if(!StringUtils.hasText(ticket)) {
            return null;
        }
        return userService.getUserByCookie(ticket,request,response);
    }

}
